from flask_login import UserMixin
from werkzeug.security import check_password_hash,generate_password_hash
import pymysql,json,datetime,json,time
from datetime import datetime
dbhost='localhost'
dbuser='root'
dbpassword='123456'
dbdatabase='renren_fast'
printsql=True

class User(UserMixin):
	def __init__(self,username,password,id):
		self.username = username
		self.password = password
		# self.id = id
		self.userId = id
	@staticmethod
	def queryUser(username):
		db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
		cursor = db.cursor()
		sql = "SELECT * from sys_user WHERE  username ='"+str(username)+"'"
		if printsql:print(sql)
		try:
			cursor.execute(sql)
			dataList1 = cursor.fetchall()
			dataList=[]
			for i in range(len(dataList1)):
				dataList.append({'userId':dataList1[i][0],'username':dataList1[i][1],'password':dataList1[i][2],'email':dataList1[i][4],'mobile':dataList1[i][5],'status':dataList1[i][6],'createUserId':dataList1[i][7],'createTime':dataList1[i][8]})
		except Exception as e:
			return "Error: unable to fetch data from sys_user"+str(e)
		db.close()
		if len(dataList):
			return User(dataList[0]['username'],dataList[0]['password'],dataList[0]['userId'])
		else:
			return None
	def verifyPassword(self,password):
		# if self.password_hash is None:
			# return False
		# return check_password_hash(self.password_hash,password)
		if self.password==password:return True
		else:return False
		
	def get_id(self):
		return self.userId

	def get(user_id):
		db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
		cursor = db.cursor()
		sql = "SELECT * from sys_user WHERE  user_id ='"+str(user_id)+"'"
		if printsql:print(sql)
		try:
			cursor.execute(sql)
			dataList1 = cursor.fetchall()
			dataList=[]
			for i in range(len(dataList1)):
				dataList.append({'userId':dataList1[i][0],'username':dataList1[i][1],'password':dataList1[i][2],'email':dataList1[i][4],'mobile':dataList1[i][5],'status':dataList1[i][6],'createUserId':dataList1[i][7],'createTime':dataList1[i][8]})
		except Exception as e:
			return "Error: unable to fetch data from sys_user"+str(e)
		db.close()
		if len(dataList):
			return User(dataList[0]['username'],dataList[0]['password'],dataList[0]['userId'])
		else:
			return None

def getAfterTime(n=5):  # n分钟之后时间
	nowtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 获取当前时间
	# 将当前时间转换为时间数组
	# print(nowtime)
	timeArray1= time.strptime(nowtime, "%Y-%m-%d %H:%M:%S")
	# print(timeArray1)
	# 将时间转换为时间戳:
	timeStamp = int(time.mktime(timeArray1))
	# print(timeStamp)
	#在原来时间戳的基础上加n*60
	timeStamp += (n * 60)
	# print(timeStamp)
	#把timestamp处理之后转换为时间数组，格式化为需要的格式
	timeArray2 = time.localtime(timeStamp)
	# print(timeArray2)
	aftertime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray2)
	# print(aftertime)
	return aftertime
class Captcha():
	def __init__(self,uuid,code):
		self.uuid=uuid
		self.code=str(code).lower()
		self.expireTime=getAfterTime()
	def save(self):#save to db
		#set expired time
		db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
		cursor = db.cursor()
		sql = '''insert into sys_captcha (uuid,code,expire_time) values('''+"'"+str(self.uuid)+"','"+str(self.code)+"','"+str(self.expireTime)+"')"
		if printsql:print(sql)
		try:
			cursor.execute(sql)
			db.commit()
		except Exception as e:
			db.rollback()
			return "Error: unable to save data from sys_captcha"+str(e)
		db.close()
	def verify(self):
		#verify uuid and code,delete uuid,and delete all expired uuid
		db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
		cursor = db.cursor()
		sql = "SELECT * from sys_captcha WHERE  uuid ='"+str(self.uuid)+"' and code='"+str(self.code)+"'"
		if printsql:print(sql)
		try:
			cursor.execute(sql)
			dataList1 = cursor.fetchall()
			dataList=[]
			for i in range(len(dataList1)):
				dataList.append({'uuid':dataList1[i][0],'code':dataList1[i][1]})
		except Exception as e:
			return "Error: unable to fetch data from sys_user"+str(e)
		db.close()
		if len(dataList):
			db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
			cursor = db.cursor()
			sql = "delete from sys_captcha WHERE  uuid ='"+str(self.uuid)+"'"
			if printsql:print(sql)
			try:
				cursor.execute(sql)
				db.commit()
			except Exception as e:
				db.rollback()
				data={
				  'msg': 'fail'+str(e),
				  'code': 1
				}
				return json.dumps(data,default=json_encoder)
			finally:
				db.close()
			return True
		else:
			return None
		